from usermanager import VIPManager
from qqapi import BotClient
import time
import json
from typing import Optional, Dict, Any
from socketcc import OneBotServer
from queue import Queue, Empty
from aiapi import AIClient
from threading import Thread
# 创建消息队列
message_queue = Queue()
myself = "3526688793"
def message_deal(data):
    # print(f"收到消息 {json.dumps(data, indent=4, ensure_ascii=False, sort_keys=True)}")
    if data["post_type"] == "message":
        print(f"收到消息 {json.dumps(data, indent=4, ensure_ascii=False, sort_keys=True)}")
        message_queue.put(data)

def message_worker():
    print("开始回复消息")
    while True:
        try:
            # 阻塞等待新消息（可加 timeout 避免卡死）
            data = message_queue.get(timeout=1)
            msgtype = data["message_type"]

            if msgtype == "private": # 私聊消息

                user_id = data["user_id"]
                text = data["raw_message"]
                print(f"🛠️  处理消息: {text}")
                with VIPManager("userlist.db") as db:
                    db.message_record(user_id, text, msg_type='query')
                    historymsg = db.get_message_history(user_id,10)
                    print(f"{user_id}历史消息{historymsg}")
                    msglist=[]
                    for histmag in historymsg:
                        if histmag["msg_type"] == "query":
                            msglist.append(
                                {
                                    'role': 'user',
                                    'content':histmag["message_text"] 
                                }
                            )
                        elif histmag["msg_type"] == "reply":
                            msglist.append(
                                {
                                    'role': 'assistant',
                                    'content':histmag["message_text"] 
                                }
                            )
                    mAIClient = AIClient()
                    retmsg = mAIClient.post(msglist)
                    # print(f"ces{msglist}")
                    # retmsg ="---"
                    print(f"准备回复 {retmsg}")
                    with BotClient() as qqbot:  
                        data = {
                            "user_id": user_id,
                            "message": retmsg,
                            "auto_escape": False
                        }
                        qqbot.post("/send_private_msg",data)
                    db.message_record(user_id, retmsg, msg_type='reply')
                message_queue.task_done()  # 标记任务完成
            elif msgtype == "group":
                print("群组消息-")
                group_id = data["group_id"]
                topmsg_type = data["message"][0]["type"]
                if topmsg_type == "at":
                    print("--- {}  {}")
                    if data["message"][0]["data"]["qq"] == myself and data["message"][1]["type"] == "text":
                        print("呼叫消息")
                        text = data["message"][1]["data"]["text"]
                        senderid = data["sender"]["user_id"]
                        nickname = data["sender"]["nickname"]
                        print(f"处理呼叫消息: {text}")
                        with VIPManager("userlist.db") as db:
                            db.record_group_message(group_id,senderid, text, nickname,msg_type='query')
                            historymsg = db.get_group_message_history(group_id,10,senderid)
                            print(f"{group_id}历史消息{historymsg}")
                            msglist=[]
                            for histmag in historymsg:
                                if histmag["msg_type"] == "query":
                                    msglist.append(
                                        {
                                            'role': 'user',
                                            'content':histmag["message_text"] 
                                        }
                                    )
                                elif histmag["msg_type"] == "reply":
                                    msglist.append(
                                        {
                                            'role': 'assistant',
                                            'content':histmag["message_text"] 
                                        }
                                    )
                            mAIClient = AIClient()
                            retmsg = f"[CQ:at,qq={senderid}] " + mAIClient.post(msglist)
                            # print(f"ces{msglist}")
                            # retmsg ="---"
                            print(f"准备回复 {retmsg}")
                            with BotClient() as qqbot:  
                                data = {
                                    "group_id": group_id,
                                    "message": retmsg,
                                    "auto_escape": False
                                }
                                qqbot.post("/send_group_msg",data)
                            db.record_group_message(group_id,senderid,mAIClient.post(msglist), "小白",msg_type='reply')
                        message_queue.task_done()  # 标记任务完成
                    else:
                        print("没有at 我自己")
                else:
                    print("日常消息")
        except Empty:
            continue
        except Exception as e:
            print(f"处理消息出错: {e}")

if __name__ == "__main__":
    print("test 开始")

    # 开启服务监控
    server = OneBotServer(host="0.0.0.0", port=8080)
    # 注册回调：
    server.on_path("/", message_deal) 
    server.start()
    messagedeal = Thread(target=message_worker, daemon=True)
    messagedeal.start()
    viplist = []
    with VIPManager("userlist.db") as db:
        db.add_vip("2213006005", "2025-09-01 00:00:00", "2025-10-01 00:00:00")
        # db.add_vip("987654321", "2025-09-10 00:00:00", "2025-12-10 00:00:00")
        for item in db.get_active_vips():
            viplist.append(item[0])
        print(viplist)
    while True:
        # print("run ...")
        time.sleep(5)